﻿using System.Windows;

namespace SHomeWorkshop.LunarPresentation.Commands
{
    public partial class Command
    {
        public static Expressions.LeafPanel InsertSameLevelLeaf()
        {
            if (Globals.selectedEditor == null) return null;
            if (Globals.selectedEditor.SelectedExpression == null) return null;

            LunarPresentation.Expressions.Expression curEx
                = Globals.selectedEditor.SelectedExpression;

            if (curEx is Expressions.LeafPanel == false)
            {
                MessageBox.Show("请先选中一个叶面板！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return null;
            }

            Expressions.LeafPanel curLeaf = curEx as Expressions.LeafPanel;

            if (curLeaf.LeafType == Expressions.LeafPanel.LeafPanelType.Root)
            {
                //叶首面板不允许插入同级叶。
                return Command.InsertNextLevelLeaf();
            }

            if (curLeaf.ParentExpression == null ||
                curLeaf.ParentExpression is Expressions.Tree == false)
            {
                MessageBox.Show("发生意外，此叶面板不在任何树中！", Globals.appName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return null;
            }

            Expressions.Tree pTree = curLeaf.ParentExpression as Expressions.Tree;

            ModifingItem mi = new ModifingItem() { OldSelectedExID = curLeaf.ExID };

            Expressions.LeafPanel newLeaf = pTree.InsertSameLevelLeaf(curLeaf, mi);
            if (newLeaf != null)
            {
                pTree.Editor.Do(mi);
                pTree.Editor.IsModified = true;

                pTree.Editor.SelectedExpression = newLeaf;
                mi.NewSelectedExID = newLeaf.ExID;
            }

            return newLeaf;
        }
    }
}
